// 隐私设置页面
const auth = require('../../utils/auth.js');
const app = getApp();

Page({
  data: {
    userInfo: {},
    loading: true,
    
    // 隐私设置项
    privacySettings: {
      dataCollection: true,          // 数据收集
      personalizedRecommend: true,   // 个性化推荐
      behaviorAnalysis: false,       // 行为分析
      locationServices: false,       // 位置服务
      thirdPartyShare: false,        // 第三方分享
      marketingMessages: true,       // 营销信息
      dataRetention: '2years'        // 数据保留期限
    },
    
    // 数据保留期限选项
    retentionOptions: [
      { value: '1year', label: '1年' },
      { value: '2years', label: '2年' },
      { value: '3years', label: '3年' },
      { value: 'forever', label: '永久保留' }
    ],
    
    showRetentionPicker: false
  },

  onLoad: function() {
    this.loadUserInfo();
    this.loadPrivacySettings();
  },

  // 加载用户信息
  loadUserInfo: function() {
    const userInfo = auth.getCurrentUser && auth.getCurrentUser();
    if (userInfo) {
      this.setData({
        userInfo: userInfo,
        loading: false
      });
    } else {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

  // 加载隐私设置
  loadPrivacySettings: function() {
    const apiBaseUrl = app.globalData.apiBaseUrl;
    
    wx.request({
      url: `${apiBaseUrl}/user/privacy/settings`,
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + auth.getToken()
      },
      success: (res) => {
        if (res.data && res.data.success) {
          // 转换字段名，适配前端
          const settings = res.data.data;
          this.setData({
            privacySettings: {
              dataCollection: settings.data_collection,
              personalizedRecommend: settings.personalized_recommend,
              behaviorAnalysis: settings.behavior_analysis,
              locationServices: settings.location_services,
              thirdPartyShare: settings.third_party_share,
              marketingMessages: settings.marketing_messages,
              dataRetention: settings.data_retention
            }
          });
        }
      },
      fail: (error) => {
        console.error('加载隐私设置失败:', error);
      }
    });
  },

  // 切换隐私设置项
  togglePrivacySetting: function(e) {
    const settingKey = e.currentTarget.dataset.key;
    const currentValue = this.data.privacySettings[settingKey];
    
    this.setData({
      [`privacySettings.${settingKey}`]: !currentValue
    });
    
    this.savePrivacySettings();
  },

  // 显示数据保留期限选择器
  showRetentionPicker: function() {
    this.setData({
      showRetentionPicker: true
    });
  },

  // 选择数据保留期限
  onRetentionChange: function(e) {
    const selectedIndex = e.detail.value;
    const selectedValue = this.data.retentionOptions[selectedIndex].value;
    
    this.setData({
      'privacySettings.dataRetention': selectedValue,
      showRetentionPicker: false
    });
    
    this.savePrivacySettings();
  },

  // 取消选择
  onRetentionCancel: function() {
    this.setData({
      showRetentionPicker: false
    });
  },

  // 保存隐私设置
  savePrivacySettings: function() {
    const apiBaseUrl = app.globalData.apiBaseUrl;
    
    // 转换字段名，适配后端
    const settings = this.data.privacySettings;
    const backendSettings = {
      data_collection: settings.dataCollection,
      personalized_recommend: settings.personalizedRecommend,
      behavior_analysis: settings.behaviorAnalysis,
      location_services: settings.locationServices,
      third_party_share: settings.thirdPartyShare,
      marketing_messages: settings.marketingMessages,
      data_retention: settings.dataRetention
    };
    
    wx.request({
      url: `${apiBaseUrl}/user/privacy/settings`,
      method: 'POST',
      header: {
        'Authorization': 'Bearer ' + auth.getToken(),
        'Content-Type': 'application/json'
      },
      data: backendSettings,
      success: (res) => {
        if (res.data && res.data.success) {
          console.log('隐私设置保存成功');
        } else {
          wx.showToast({
            title: '保存失败',
            icon: 'error'
          });
        }
      },
      fail: (error) => {
        console.error('保存隐私设置失败:', error);
        wx.showToast({
          title: '保存失败',
          icon: 'error'
        });
      }
    });
  },

  // 查看隐私政策
  viewPrivacyPolicy: function() {
    const apiBaseUrl = app.globalData.apiBaseUrl;
    
    wx.request({
      url: `${apiBaseUrl}/user/privacy/policy`,
      method: 'GET',
      success: (res) => {
        if (res.data && res.data.success) {
          const policy = res.data.data;
          wx.navigateTo({
            url: `/pages/legal/document?type=privacy&title=${encodeURIComponent(policy.title)}&content=${encodeURIComponent(policy.content)}`
          });
        } else {
          wx.showModal({
            title: '隐私政策',
            content: '隐私政策加载失败，请稍后再试。',
            showCancel: false,
            confirmText: '知道了'
          });
        }
      },
      fail: (error) => {
        console.error('获取隐私政策失败:', error);
        wx.showModal({
          title: '隐私政策',
          content: '隐私政策加载失败，请检查网络连接。',
          showCancel: false,
          confirmText: '知道了'
        });
      }
    });
  },

  // 查看用户协议
  viewUserAgreement: function() {
    const apiBaseUrl = app.globalData.apiBaseUrl;
    
    wx.request({
      url: `${apiBaseUrl}/user/privacy/agreement`,
      method: 'GET',
      success: (res) => {
        if (res.data && res.data.success) {
          const agreement = res.data.data;
          wx.navigateTo({
            url: `/pages/legal/document?type=agreement&title=${encodeURIComponent(agreement.title)}&content=${encodeURIComponent(agreement.content)}`
          });
        } else {
          wx.showModal({
            title: '用户协议',
            content: '用户协议加载失败，请稍后再试。',
            showCancel: false,
            confirmText: '知道了'
          });
        }
      },
      fail: (error) => {
        console.error('获取用户协议失败:', error);
        wx.showModal({
          title: '用户协议',
          content: '用户协议加载失败，请检查网络连接。',
          showCancel: false,
          confirmText: '知道了'
        });
      }
    });
  },

  // 导出个人数据（跳转到已有的导出页面）
  exportPersonalData: function() {
    wx.navigateTo({
      url: '/pages/records/export/export'
    });
  },

  // 返回设置页面
  navigateBack: function() {
    wx.navigateBack();
  }
});
